package com.jy.oms.framework.closed;

import com.jy.oms.framework.util.SpringUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 应用关闭事件处理
 *
 * @author liuquan
 */
@Service
public class ClosedEventListenerHandler implements ApplicationListener<ContextClosedEvent> {
    private static Logger logger = LoggerFactory.getLogger(ClosedEventListenerHandler.class);

    private List<IClosedEventListener> closedEventListenerList = new ArrayList<>();

    public static ClosedEventListenerHandler getInstance() {
        return SpringUtil.getBean(ClosedEventListenerHandler.class);
    }

    @Override
    public void onApplicationEvent(ContextClosedEvent event) {
        gracefulStop();
    }

    public void registClosedEventListener(IClosedEventListener closedEventListener) {
        if (closedEventListener == null) {
            return;
        }

        closedEventListenerList.add(closedEventListener);
    }

    public void gracefulStop(){
        if (CollectionUtils.isEmpty(closedEventListenerList)) {
            return;
        }

        logger.info("开始关闭应用，开始处理关闭事件");

        for (IClosedEventListener closedEventListener : closedEventListenerList) {
            try {
                closedEventListener.onClosedEvent();
            } catch (Exception e) {
            }
        }
    }
}
